package hz.mobileproject.pda.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;

import java.util.List;

import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.request.Request_Edu_inter;
import hz.mobileproject.pda.network.UploadNetWork;

/**
 * Created by hasee on 2017/10/17.
 */

public class UploadFailService extends Service implements UploadNetWork.UploadNetworkListener{

    private DBManager mDBManager;
    private int mUploadIndex = 0;
    private List<Request_Edu_inter> mRequestInterList;
    private int mintSuccess = 0;
    private int mintFail = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mDBManager = DBManager.getInstance(getApplicationContext());
        mRequestInterList = mDBManager.queryRequest_Edu_inter();
        upload();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void upload(){
        if(!isFinish()){
            mDBManager.updateEduInterUpDown(mRequestInterList.get(mUploadIndex), "2");
            sendBroadcast2Activity("uploadStart");
            UploadNetWork uploadNetWork = new UploadNetWork();
            uploadNetWork.setUploadNetworkListener(this);
            uploadNetWork.uploadData(mRequestInterList.get(mUploadIndex));
        }else{
            sendBroadcast2Activity("uploadFinish");
            ToastUtils.showLong("上传完成，成功"+mintSuccess+"个，失败"+mintFail+"个");
            stopSelf();
        }
    }

    private void sendBroadcast2Activity(String action){
        Intent intent = new Intent();
        intent.setAction(action);
        sendBroadcast(intent);
    }

    private boolean isFinish(){
        if(null == mRequestInterList){
            return true;
        }
        return mRequestInterList.size() < mUploadIndex+1;
    }

    @Override
    public void onSuccess(int code, Request_Edu_inter inter) {
        mDBManager.updateEduInterUpDown(inter, "0");
        mDBManager.deleteRequest_Edu_inter(inter.getId());
        sendBroadcast2Activity("uploadSuccess");
        mUploadIndex++;
        mintSuccess++;
        upload();
    }

    @Override
    public void onFail(int code, Request_Edu_inter inter) {
        mDBManager.updateEduInterUpDown(inter, "1");
        sendBroadcast2Activity("uploadFail");
        mUploadIndex++;
        mintFail++;
        upload();
    }
}
